// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: "te-6b32b2"
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let count = 0
  let isLike= true
  let w= {
    _openid: wxContext.OPENID,
    q_id: event.q_id
  } 

  let qlike = await db.collection('qikan-like').where(w).get().then((res)=> {
      return res.data[0]
  })

  if (qlike) {
    await db.collection('qikan-like').where(w).update({
      data: {
        islike: !qlike.islike
      }}).then (() =>{
        if (qlike.islike) {
          count = -1,
          isLike= false
        } else {
          count = 1
        }
      })
  } else {
    await db.collection('qikan-like').add({
      data: {
        q_id: event.q_id,
        islike: true,
        _openid: wxContext.OPENID
      }
    }).then(()=> {
      count = 1
    }) 
  }
  //在期刊标记点赞次数
  //const _ = db.command
  let qk = await db.collection('qikan').where({id: event.q_id}).get().then((res)=> {
    return res.data[0]
  })
  await db.collection('qikan').where({id: event.q_id}).update({
    data: {
      likeNums: qk.likeNums + count
    }
  })
  return {
    count: count,
    isLike: isLike
  }
}